package com.example.base.job;

import com.example.base.job.systemjob.SystemJobAppExpire;
import com.example.base.job.systemjob.SystemJobDataClear;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class SystemJobManager {

    @Qualifier(value = "getSchedulerFactoryBean")
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Bean
    public void addJob(){
        addQuartz(SystemJobAppExpire.class,"appexpire","0/5 * * * * ?");
        addQuartz(SystemJobDataClear.class,"dataclear","0/5 * * * * ?");
    }


    /**
     * 添加rest调用
     */
    public void addQuartz(Class<?> cls,String groupName,String cron){
        log.info("开始添加系统定时任务了{}",cls);
        try {

            //添加执行监听器
            //schedulerFactoryBean.getScheduler().getListenerManager().addJobListener(jobListenerServer, EverythingMatcher.allJobs());

            schedulerFactoryBean.getScheduler().start();
            JobDetail jobDetail=null;

            jobDetail= JobBuilder.newJob(QuarztUtils.getClass(cls.getName()).getClass()).withIdentity(cls.getName(),groupName)
                    .build();

            // 表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(),groupName).withSchedule(scheduleBuilder).build();
            schedulerFactoryBean.getScheduler().scheduleJob(jobDetail,trigger);
            log.info("{} 系统任务添加成功",cls.getName());
        }catch (Exception e){
            log.info("系统添加失败 失败信息如下 "+e.getMessage());
        }
    }






}
